package com.gqb.ftp;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;


public class FtpUtils {
	
	public static void main(String[] args) {
		FTPClient ftp=new FTPClient();
		String path="/directoryName/11/22";
		File file=new File(path);
		int reply;
		try {
			ftp.connect("127.0.0.1", 21);
			ftp.login("admin", "gqb101112");
			reply=ftp.getReplyCode();
			if(!FTPReply.isPositiveCompletion(reply)){
				ftp.disconnect();
			}
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.setControlEncoding("utf-8");
			System.out.println(iterateDelete(ftp,new String(path.getBytes("utf-8"),"iso-8859-1")));
			/*System.out.println(ftp.changeWorkingDirectory(new String(path.getBytes("utf-8"),"iso-8859-1")));
			if(!ftp.changeWorkingDirectory(file.getPath())){
				if(changeDirectory(file.getParentFile().getPath(), file.getName(), ftp)){
					ftp.changeWorkingDirectory(file.getPath());
				}
			}
			System.out.println(ftp.changeWorkingDirectory(path));
			System.out.println(ftp.changeWorkingDirectory("/doc1"));
			FTPFile[] files=ftp.listFiles();
			ftp.setFileType(FTP.BINARY_FILE_TYPE);*/
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/** 
     *  
     *【功能描述：删除文件夹】 
     *【功能详细描述：功能详细描述】 
     * @see   【类、类#方法、类#成员】 
     * @param ftpClient 
     * @param ftpPath  文件夹的地址 
     * @return true 表似成功，false 失败 
     * @throws IOException 
     */  
    public static boolean iterateDelete(FTPClient ftpClient,String ftpPath) throws IOException{  
        FTPFile[] files = ftpClient.listFiles(ftpPath);  
        boolean flag = false;  
        for(FTPFile f:files){  
            String path = ftpPath+File.separator+f.getName();  
            if(f.isFile()){  
                // 是文件就删除文件  
                ftpClient.deleteFile(path);  
            }else if(f.isDirectory()){  
               iterateDelete(ftpClient,path);  
            }  
        }  
        // 每次删除文件夹以后就去查看该文件夹下面是否还有文件，没有就删除该空文件夹  
        FTPFile[] files2 = ftpClient.listFiles(ftpPath);   
        if(files2.length==0){  
            flag = ftpClient.removeDirectory(ftpPath);  
        }else{  
            flag = false;  
        }  
        return flag;  
    }  
	/**
	 * ��ftp��changeWorkingDirectory ���з�װ���л�������ʱ����ļ���Ϊ�������͵ݹ�Ĵ����ļ���
	 * @param pathParent ���ļ���·��
	 * @param directoryName Ҫ�������ļ���
	 * @param ftpClient ftp
	 * @return
	 * @throws IOException
	 */
	public static boolean changeDirectory(String pathParent,String directoryName,FTPClient ftpClient) throws IOException{
		File file=new File(pathParent);
		if(!ftpClient.changeWorkingDirectory(pathParent)){
			changeDirectory(file.getParentFile().getPath(), file.getName(), ftpClient);
		}else{
			ftpClient.changeWorkingDirectory(pathParent);
			ftpClient.makeDirectory(directoryName);
		}
		ftpClient.changeWorkingDirectory(pathParent);
		ftpClient.makeDirectory(directoryName);
		return true; 
	}
	
	/**
	 * 
	 * @param url ftp·��
	 * @param username 
	 * @param password
	 * @param filename �ļ���
	 * @param path ftp�ϵ�·��
	 * @param in ������
	 * @return
	 */
	public static boolean uploadFile(String url,int port,String username,String password,String filename,String path,InputStream in){
		boolean success=false;
		FTPClient ftp=new FTPClient();
		try {
			int reply;
			ftp.connect(url,port);
			ftp.login(username, password);
			reply=ftp.getReplyCode();
			if(!FTPReply.isPositiveCompletion(reply)){
				ftp.disconnect();
				return success;
			}
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.changeWorkingDirectory(path);
			ftp.storeFile(filename, in);
			in.close();
			ftp.logout();
			success=true;
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(ftp.isConnected()){
				try {
					ftp.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return success;
	}
	
	/**
	 * 
	 * @param url ftp��ַ
	 * @param port �˿�
	 * @param username ftp���û���	
	 * @param password ftp���û�������
	 * @param filename Ҫ���ڵ��ļ���
	 * @param remotePath �ļ���ftp�ϵĴ��·��
	 * @param localPath ���ص����ص�·��
	 * @return 
	 */
	public static boolean downloadFile(String url,int port,String username,String password,String filename,String remotePath,String localPath){
		boolean success=false;
		FTPClient ftp=new FTPClient();
		try {
			int reply;
			ftp.connect(url,port);
			ftp.login(username, password);
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			reply=ftp.getReplyCode();
			if(!FTPReply.isPositiveCompletion(reply)){
				ftp.disconnect();
				return success;
				
			}
			ftp.changeWorkingDirectory(remotePath);
			FTPFile[] files=ftp.listFiles();
			for (FTPFile ftpFile : files) {
				if(ftpFile.getName().equals(filename)){
					System.out.println(ftpFile.getName());
					File locaFile=new File(localPath+"/"+filename);
					OutputStream out=new FileOutputStream(locaFile);
					ftp.retrieveFile(ftpFile.getName(), out);
					out.close();
					success=true;
				}
			}
			ftp.logout();
		} catch (FileNotFoundException  e) {
			e.printStackTrace();
			System.err.println("�ļ�������");
			return false;
		} catch (IOException e) {
			System.err.println("�ļ���ȡ����");
			return false;
		}
		finally{
			if(ftp.isConnected()){
				try {
					ftp.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return success;
		
	}
}
